package com.chhuang.ewcrm.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 获取验证码
 * @author chhuang
 * @create 2020-09-26-9:25
 */
@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {
    Logger logger= LoggerFactory.getLogger(KaptchaController.class);

    @Autowired
    private Producer kaptchaProducer;

    @RequestMapping
    public void getKaptcha(HttpServletResponse response, HttpSession session) {
        // 生成验证码
        String code = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(code);

        // 将验证码存入session
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, code);

        // 将突图片输出给浏览器
        response.setContentType("image/png");
        try {
            OutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            logger.error("响应验证码失败:" + e.getMessage());
        }
    }
}
